package com.modakai.med.hosp.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.modakai.med.hosp.repository.ScheduleRepository;
import com.modakai.med.hosp.service.DepartmentService;
import com.modakai.med.hosp.service.HospitalService;
import com.modakai.med.hosp.service.ScheduleService;
import com.modakai.med.model.hosp.Schedule;
import com.modakai.med.vo.BookingScheduleRuleVo;
import com.modakai.med.vo.ScheduleQueryVo;
import lombok.RequiredArgsConstructor;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ScheduleServiceImpl implements ScheduleService {

    private final ScheduleRepository scheduleRepository;

    private final MongoTemplate mongoTemplate;

    private final HospitalService hospitalService;

    private final DepartmentService departmentService;

    @Override
    public void save(Map<String, Object> paramMap) {
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Schedule.class);
        Schedule targetSchedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());

        if (targetSchedule != null) {
            targetSchedule.setUpdateTime(new Date());
            targetSchedule.setIsDeleted(0);
            scheduleRepository.save(targetSchedule);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }
    }

    @Override
    public Page<Schedule> selectPage(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        // 1 排序
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageable = PageRequest.of(page - 1, limit, sort);

        Schedule schedule = new Schedule();
        schedule.setHoscode(scheduleQueryVo.getHoscode());
        schedule.setDepcode(scheduleQueryVo.getDepcode());
        schedule.setIsDeleted(0);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) // 修改默认字符集
                .withIgnoreCase(true);//改变默认大小写忽略方式：忽略大小写

        // 创建实例
        Example<Schedule> example = Example.of(schedule, exampleMatcher);
        return scheduleRepository.findAll(example, pageable);
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule targetSchedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hoscode);
        if (targetSchedule != null) {
            scheduleRepository.deleteById(targetSchedule.getId());
        }
    }

    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {
        // 根据医院编号和科室编号创建查询条件
        // 1 根据医院编号 和 科室编号 查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);

        // 构建聚合查询，包括匹配条件、分组、排序、分页
        // 2 根据工作日期 workDate 进行分组
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria), // 匹配条件
                Aggregation.group("workDate") // 分组字段
                        // 3 统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                // 排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),
                // 4 实现分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );

        // 执行聚合查询，返回查询结果
        // 3 调用方法， 最终执行
        AggregationResults<BookingScheduleRuleVo> aggResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResults.getMappedResults();

        // 计算总记录数，用于分页
        // 分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        long total = totalAggResults.getMappedResults().size();

        // 遍历预约规则列表，为每个规则设置工作日的星期几
        // 4 把日期对应星期获取
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            // 使用当前日期获取该日期是星期几
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            // 将星期几保存回规则vo中
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        // 准备返回的数据映射
        // 5 设置最终数据，进行返回
        HashMap<String, Object> result = new HashMap<>();
        // 将处理后的预约规则列表放入返回结果中
        result.put("bookingScheduleRuleList", bookingScheduleRuleVoList);
        // 将总数放入返回结果中
        result.put("total", total);

        // 获取医院名称
        // 获取医院名称
        String hosName = hospitalService.getHospName(hoscode);
        // 准备基础信息映射
        HashMap<String, String> baseMap = new HashMap<>();
        // 将医院名称放入基础信息映射中
        baseMap.put("hosname", hosName);
        // 将基础信息映射放入返回结果中
        result.put("baseMap", baseMap);

        // 返回处理后的结果
        return result;

    }

    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        // 1 查询mongo中的数据
        List<Schedule> scheduleList = scheduleRepository
                .findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());

        // 2. 封装医院名称 科室名称 日期对应星期
        scheduleList.forEach(this::packageSchedule);

        return scheduleList;
    }

    private void packageSchedule(Schedule schedule) {
        // 封装医院名称
        schedule.getParam().put("hosname", hospitalService.getHospName(schedule.getHoscode()));

        // 封装科室名称
        schedule.getParam().put("depname", departmentService.getDepartName(schedule.getHoscode(), schedule.getDepcode()));

        // 设置日期对应星期
        schedule.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }

    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }
}
